<template>
    <div>
      <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        top="30%"
        size="tiny"
        :before-close="handleClose"
         class="login-dialog">

        <!--登录框-->
          <el-form :model="loginForm" :rules="loginrules" v-show="show" ref="loginForm" label-width="100px" id="loginForm">
            <el-form-item label="用户名" prop="name">
              <el-input type="text" v-model="loginForm.name" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="pass">
              <el-input type="password" v-model="loginForm.pass" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item class="loginbutton">
              <el-button type="primary" @click="submitForm('loginForm')">登录</el-button>
              <el-button @click="resetForm('loginForm')">重置</el-button>
            </el-form-item>
            <el-form-item class="toRegister">
              <span @click="changeSwitch('regisetr')" style="cursor:pointer">注册</span>
            </el-form-item>
          </el-form>
        <!--注册框-->
          <el-form :model="registerFrom" :rules="registerRules" v-show="!show" ref="registerFrom" label-width="100px" id="registerFrom" style="display:none">
            <el-form-item label="用户名" prop="name">
              <el-input v-model="registerFrom.name" placeholder="字母丶数字 5-8位"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="pass">
              <el-input type="password" v-model="registerFrom.pass" auto-complete="off" placeholder="字母丶数字和符号 6-12位"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPass">
              <el-input type="password" v-model="registerFrom.checkPass" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item class="loginbutton">
              <el-button type="primary" @click="submitregForm('registerFrom')">注册</el-button>
              <el-button @click="resetForm('registerFrom')">重置</el-button>
            </el-form-item>
            <el-form-item class="toRegister">
              <span @click="changeSwitch('login')" style="cursor:pointer">登录</span>
            </el-form-item>
          </el-form>
      </el-dialog>
    </div>
</template>
<script>
  import Axios from 'axios'
  import {mapActions,mapGetters} from 'vuex'
  import MD5 from 'js-md5';
    export default {
    data() {
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          callback();
        }
      };
      var validateName = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入用户名'));
        }else {
          callback();  
        }
      };
       var regName = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入用户名'));
        } else {
          var reg=/^[a-zA-Z0-9]{5,8}$/g;
          if(reg.test(value)){
            callback();
          }else{
            callback(new Error('用户名格式不正确'));
          }
        }
      };
      var regPass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.registerFrom.checkPass !== '') {
            this.$refs.registerFrom.validateField('checkPass');
          }
          callback();
        }
      };
      var regCkpass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.registerFrom.pass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        dialogVisible: true,
        title:'登录',
        show:true,
        loginForm: {
          name:'',
          pass: '',
        },
        loginrules: {
          pass: [
            { validator: validatePass, trigger: 'blur' }
          ],
          name: [
            { validator: validateName, trigger: 'blur' }
          ],
        },
        registerFrom: {
          name:'',
          pass: '',
          checkPass: '',
        },
        registerRules: {
          pass: [
            { validator: regPass, trigger: 'blur' }
          ],
          checkPass: [
            { validator: regCkpass, trigger: 'blur' }
          ],
          name: [
            { validator: regName, trigger: 'blur' }
          ]
        }
      };
    },
    methods: {
      ...mapActions(['updatedlogin','setPass','setName']),
      handleClose(done) {
        return;
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var name = this.loginForm.name;
            var pass = MD5(this.loginForm.pass);
            Axios({
              method:"post",
              url:'http://localhost:3000/users/login',
              data:{
                name:name,
                password:pass,
              },
              dataType:'json'
            }).then((d)=>{
              if(d.data && d.data.name.trim().length >0){
                this.$message({
                  showClose: true,
                  message: '登录成功！',
                  type: 'success'
                });
                this.updatedlogin(true);
                this.setName(name);
                this.setPass(this.loginForm.pass);
                this.$router.push('/')
              }else{
                this.$message({
                  showClose: true,
                  message: '用户名不存在或者密码错误!',
                  type: 'warning'
                });
              }
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      submitregForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var name = this.registerFrom.name;
            var pass = MD5(this.registerFrom.pass);
            Axios({
              method:'post',
              url:'http://localhost:3000/users/register',
              data:{
                name:name,
                password:pass,
              },
              dataType:'json'
            }).then((d)=>{
              if(d.data.msg){
                this.$message({
                  showClose: true,
                  message: '该用户名已经存在',
                  type: 'warning'
                });
              }else{
                this.$message({
                  showClose: true,
                  message: '注册成功！',
                  type: 'success'
                });
                this.show=true;
                this.title="登录"
                this.$refs['loginForm'].resetFields();
                this.$refs['registerFrom'].resetFields(); 
              }
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      changeSwitch(val){
        if(val!=='login'){
          this.show = false;
          this.title="注册"
          this.$refs['loginForm'].resetFields();
          this.$refs['registerFrom'].resetFields(); 
        }else{
          this.show = true;
          this.title="登录"
          this.$refs['loginForm'].resetFields();
          this.$refs['registerFrom'].resetFields(); 
        }
        
      }
    },
    computed:{
      ...mapGetters(['login'])
    }
  }
</script>

<style  lang="scss" >
   .el-dialog__title{
     display:block;
     margin:0 auto;
     width:auto;
     text-align:center;
   }
   .login-dialog{
        background:#324057;
   }
   .el-icon-close{
     display:none;
   }
   .el-dialog__body{
     padding:30px 40px 0px 0px;
   }
   .loginbutton{
      margin-bottom:0px;
      .el-form-item__content{
        margin-left:150px !important;
      }
   }
   .toRegister{
     margin-bottom:0px;
     span{
      font-size:12px;
      float:right;
     } 
   }
</style>